import React, { useEffect, useState,useRef } from 'react';
import { Input,Button } from 'antd';
import {useDispatch, useSelector} from 'react-redux';
import './chat.css';
const { TextArea } = Input;

function Chat(){
    const ws = useRef(null);
    const [message,setMessage] = useState("");
    const user = useSelector(state => state.user.user);
    const [chatContent,setChatContent] = useState([]);

    function handleSend(){
        ws.current.send(JSON.stringify({...user,message}));
    }
    
    useEffect(() => {
        ws.current = new WebSocket("ws://localhost:3001/socket/connect/"+user._id);
        ws.current.onmessage = function(event){
            setChatContent(JSON.parse(event.data));
        }
    },[])
    return <div>
        <h3>聊天室</h3>
        <div className="chat-box">
            {
                chatContent.map((element) => {
                    if(element._id == user._id){
                        return <p key={element._id} className="me">我说：{element.message}</p>
                    }else{
                        return <p key={element._id} className="other">{element.username}说：{element.message}</p>
                    }
                })
            }
        </div>
        <TextArea rows={4} value={message} onChange={(e) => setMessage(e.target.value)} />
        <Button onClick={handleSend} type="primary">发送</Button>
    </div>
}

export default Chat;